package com.yztc.xiami_app.ui.activity.guide;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.yztc.xiami_app.R;
import com.yztc.xiami_app.constant.OtherConstant;
import com.yztc.xiami_app.constant.URLConstant;
import com.yztc.xiami_app.http.HttpUtils;
import com.yztc.xiami_app.ui.activity.MainActivity;
import com.yztc.xiami_app.ui.versionupdate.DownloadIntentService;
import com.yztc.xiami_app.ui.versionupdate.Version;
import com.yztc.xiami_app.utils.PreUtils;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SplashActivity extends Activity {


    //是否进入主画面key
    public static final String KEY_GOTO_MAIN = "KEY_GOTO_MAIN";

    private Context mContext;
    private String versionUrl; //新版本的APP的下载地址

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg .what == 10){
                //网络加载完成,弹出对话框，询问用户是否需要更新APP
                askForUpdateVersion(URLConstant.VersionCode.URL_VERSION_BASE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        mContext = this;

        //开启延时2秒的子线程
        new Thread(new SplashRunnable()).start();
    }

    //显示询问用户是否更新APP的dialog
    private void showHintDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setIcon(R.mipmap.xiamilogo)
                .setMessage("检测到当前有新版本，是否更新?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //取消更新，则跳转到旧版本的APP的页面
                        goToWhere();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //开启IntentService，下载最新版本的APP
                        //开启IntentService服务，下载
                        Intent intent = new Intent(SplashActivity.this, DownloadIntentService.class);
                        intent.putExtra(OtherConstant.KEY_NEW_VERSION_APK,versionUrl);
                        startService(intent);
                    }
                }).create().show();


    }


    //询问用户是否更新APP版本
    private void askForUpdateVersion(String baseUrl) {
        HttpUtils.getVersionData(baseUrl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Version>() {
                    @Override
                    public void onCompleted() {
                        Log.i("tag","---------->onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("tag","---------->onError");
                    }

                    @Override
                    public void onNext(Version version) {
                        Log.i("tag","---------->onNext");
                        int newVersionCode = version.getData().getVersion();
                       versionUrl = version.getData().getVsersion_url();

                        //获取当前app版本
                        int currVersionCode = getVersionCode(mContext);

                        //如果当前版本小于新版本，则更新
                        if(currVersionCode < newVersionCode){
                            Log.i("tag","有新版本需要更新");
                            showHintDialog();
                        }
                    }
                });
    }

    //进入那个画面
    private void goToWhere() {
        //是否进入主画面
        boolean isGotoMain = PreUtils.readBoolean(SplashActivity.this, KEY_GOTO_MAIN);
        Intent intent = new Intent();
        if (isGotoMain) {
            //进入主画面
            intent.setClass(SplashActivity.this, MainActivity.class);
        } else {
            //进入引导画面
            intent.setClass(SplashActivity.this, GuideActivity.class);
            PreUtils.writeBoolean(SplashActivity.this, KEY_GOTO_MAIN, true);
        }
        startActivity(intent);
        finish();
    }

    //获取当前APP的版本号（VersionCode）
    private int getVersionCode(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        int versionCode = 0;
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    //闪屏画面，延时2秒的异步任务
    class SplashRunnable implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(1000);

                //网络加载的初始化完成，给主线程发消息
                Message msg = Message.obtain();
                msg.what = 10;
                handler.sendMessage(msg); //发送消息
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
